package com.jumi.microservice.service.logistics.express;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jumi.microservice.common.utils.HttpClientUtils;
import com.jumi.microservice.dto.logistics.Logistics;
import com.jumi.microservice.dto.logistics.LogisticsSearchRequest;
import com.jumi.microservice.dto.logistics.LogisticsSearchResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author by mazhao
 * 中国邮政快递
 * @Classname ChinaPostExpress
 * @Description TODO
 * @Date 2020/8/21 14:31
 */
@Service
public class ChinaPostExpress extends ResponseController implements Express {

    private static final Logger log = LoggerFactory.getLogger(ChinaPostExpress.class);

    @Resource
    HttpClientUtils httpClientUtils;

    @Override
    public String expressCode() {
        return "YZPY";
    }

    @Override
    public LogisticsSearchResponse logisticsSearch(LogisticsSearchRequest request) {
        log.info("邮政快递包裹查询参数[{}]", JSON.toJSONString(request));
        JSONArray jsonArray = null;
        try {
            String url = "http://211.156.193.140:8000/cotrackapi/api/track/mail/";
            //拼接请求头
            Map<String,String> headers = new HashMap<>(2);
            headers.put("Version","ems_track_cn_1.0");
            headers.put("authenticate","79F65BC607B7215DE053D2C2020A7810");
            //组建数据格式
            url = url+request.getLogisticsNo();
            //发送请求并接受返回
            String res = httpClientUtils.get(url, headers);
            //处理返回结果
            log.info("请求返回结果[{}]",res);
            JSONObject json = JSONObject.parseObject(res);
            jsonArray = json.getJSONArray("traces");
        } catch (Exception e) {
            log.error("邮政快递包裹查询出错[{}]",e.getMessage());
        }
        LogisticsSearchResponse logisticsSearchResponse = checkResult(jsonArray,request);
        return controller(logisticsSearchResponse,jsonArray,"remark","acceptTime");
    }

}
